package com.angenela.imageshare.ui.publish;

import android.Manifest;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.angenela.imageshare.R;
import com.angenela.imageshare.databinding.FragmentPublishBinding;
import com.angenela.imageshare.dto.ImageDTO;
import com.angenela.imageshare.pojo.Tag;
import com.angenela.imageshare.util.TagUtil;
import com.angenela.imageshare.util.UriUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class PublishFragment extends Fragment {

    private static final String IMAGE_UPLOAD_URL = "http://122.9.152.182:8080/image/upload";
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private final int REQUEST_EXTERNAL_STORAGE = 1;
    private PublishViewModel publishViewModel;
    private FragmentPublishBinding binding;
    private Integer tagId = 0;
    private Uri imageUri;
    private ImageView image;
    private Button selectBtn;
    private Button publishBtn;
    private String imagePath = null;

    public ImageDTO uploadImage(Uri imageUri, Integer id, Integer tagId) throws IOException, JSONException {
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File(imagePath);

        RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "file", image)
                .addFormDataPart("userId", String.valueOf(id))
                .addFormDataPart("tagId", String.valueOf(tagId))
                .build();

        Request request = new Request.Builder()
                .url(IMAGE_UPLOAD_URL)
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        ObjectMapper mapper = new ObjectMapper();
        ImageDTO result = mapper.readValue(response.body().string(), ImageDTO.class);

        return result;
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        publishViewModel = new ViewModelProvider(this).get(PublishViewModel.class);
        binding = FragmentPublishBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 从相册选取图片
        image = binding.imageShow;
        selectBtn = binding.btnAlbum;
        selectBtn.setOnClickListener((view) -> {
            //申请权限部分
            String write = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            String read = Manifest.permission.READ_EXTERNAL_STORAGE;

            final String[] WriteReadPermission = new String[]{write, read};

            int checkWrite = ContextCompat.checkSelfPermission(getContext(), write);
            int checkRead = ContextCompat.checkSelfPermission(getContext(), read);
            int ok = PackageManager.PERMISSION_GRANTED;

            if (checkWrite != ok && checkRead != ok) {
                //申请权限，读和写都申请一下，不然容易出问题
                ActivityCompat.requestPermissions(getActivity(), WriteReadPermission, 1);
            } else {
                openAlbum();
            }
        });


        // 设置tag单选框
        RadioGroup radioGroup = binding.radioGroup;
        List<Tag> tags = TagUtil.getData();
        for (int i = 0; i < tags.size(); i++) {
            RadioButton radioButton = new RadioButton(getContext());
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            //设置RadioButton边距 (int left, int top, int right, int bottom)
            lp.setMargins(15, 0, 0, 0);
            //设置RadioButton的样式
            radioButton.setButtonDrawable(R.drawable.radio_bg);
            //设置文字距离四周的距离
            radioButton.setPadding(10, 0, 50, 0);
            //设置文字
            radioButton.setText(tags.get(i).getName());
            //设置radioButton的点击事件
            final int finalI = i + 1;
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tagId = finalI;
                    System.out.println(tagId);
                }
            });
            //将radioButton添加到radioGroup中
            radioGroup.addView(radioButton);
        }


        // 设置上传事件
        publishBtn = binding.btnPublish;
        publishBtn.setOnClickListener((view) -> {
            try {
                uploadImage(imageUri, getUserId(), tagId);
                Toast.makeText(getContext(), "上传成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });

        return root;
    }

    public Integer getUserId() {
        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String idKey = resources.getString(R.string.login_account_id);
        SharedPreferences sharedPreferences =
                getActivity().getSharedPreferences(spFileNameKey, Context.MODE_PRIVATE);
        return sharedPreferences.getInt(idKey, 0);
    }

    void openAlbum() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 123);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            openAlbum();
        else Toast.makeText(getContext(), "你拒绝了打开相册的权限", Toast.LENGTH_SHORT).show();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 123:
                handleImageOnKitKat(data);
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getContext(), uri)) {
            //如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];  //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的Uri，直接获取图片路径即可
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); //根据图片路径显示图片
    }

    //将选择的图片Uri转换为路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //展示图片
    private void displayImage(String imagePath) {
        if (imagePath != null && !imagePath.equals("")) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            image.setImageBitmap(bitmap);
            publishBtn.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}